package cn.appsys.controller.backend;


import cn.appsys.pojo.BackendUser;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.service.backend.BackendUserService;
import cn.appsys.service.developer.DataDictionaryService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/manager/backend/user")
public class BackendUserController {

    private Logger logger = Logger.getLogger(UserLoginController.class);

    @Resource
    BackendUserService backendUserServiceImpl;

    @Resource
    DataDictionaryService dataDictionaryServiceImp;

    @RequestMapping(value = "/list")
    public String list(Model model, BackendUser backendUser,
                      /* @RequestParam(value = "userCode", required = false) String userCode,
                       @RequestParam(value = "userName", required = false) String userName,
                       @RequestParam(value = "userType", required = false) Integer userType,*/
                       @RequestParam(value = "pageIndex", required = false) String pageIndex) {
        //页面容量,页面显示的大小
        int pageSize = Constants.pageSize;
        //当前页码
        Integer currentPageNo = 1;
        List<BackendUser> backendUserList = null;
        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        try {
            backendUserList = backendUserServiceImpl.getBackendUserListBiz(backendUser, currentPageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //总数量（表）
        int totalCount = 0;
        try {
            totalCount = backendUserServiceImpl.getBackendUserCountBiz(backendUser);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        model.addAttribute("backendUserList", backendUserList);
        model.addAttribute("pages", pages);
        model.addAttribute("userType", backendUser.getUserType());
        model.addAttribute("userCode", backendUser.getUserCode());
        model.addAttribute("userName", backendUser.getUserName());
        return "backend/user/list";
    }

    @RequestMapping(value = "backenduserview")
    public String backendUserView(Integer id) {
        logger.info("id:" + id);
        //去数据库中根据id获得 BackendUser 对象实例返回给页面
        return "backend/user/view";
    }

    /**
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getdatadictionary")
    public Object getDataDictionary(@RequestParam(value = "id", required = false) Integer id) {
        List<DataDictionary> dictionaryList = null;
        try {
            dictionaryList = dataDictionaryServiceImp.getDataDictionaryList("USER_TYPE");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONArray.toJSONString(dictionaryList);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/backenduserview")
    public Object backendUserView(Model model, @RequestParam(value = "id") int id) {
        BackendUser backendUser = null;
        try {
            backendUser = backendUserServiceImpl.getByBackendUserIdBiz(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("backendUser", backendUser);
        return "backend/user/view";
    }

    @ResponseBody
    @RequestMapping(value = "/delByBackendUserId", method = RequestMethod.GET)
    public Object delByBackendUserId(@RequestParam(value = "id") int id) {
        logger.info("id:" + id);
        Map<String, String> map = new HashMap();
        try {
            if (backendUserServiceImpl.delByBackendUserIdBiz(id) > 0) {
                map.put("delResult", "true");
            } else {
                map.put("delResult", "false");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONArray.toJSONString(map);
    }

    @RequestMapping(value = "/toadd", method = RequestMethod.GET)
    public String toAdd() {
        System.out.println("add............");
        return "backend/user/add";
    }

    @RequestMapping(value = "/add")
    public String add(BackendUser backendUser, HttpSession session) {
        System.out.println("add............");
        BackendUser user = (BackendUser) session.getAttribute("userSession");
        backendUser.setCreatedBy(user.getId());
        backendUser.setCreationDate(new Date());
        System.out.println(backendUser.toString());
        int count = 0;
        try {
            count = backendUserServiceImpl.addBackendUserBiz(backendUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (count > 0) {
            return "redirect:/manager/backend/user/list";
        } else {
            return "backend/user/add";
        }
    }

    @RequestMapping(value = "/getbackenduserbyid")
    public String getBackendUserById(Model model, @RequestParam(value = "id") int id) {
        BackendUser backendUser = null;
        try {
            backendUser = backendUserServiceImpl.getByBackendUserIdBiz(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("backendUser", backendUser);
        return "backend/user/update";
    }

    @RequestMapping(value = "update")
    public String update(BackendUser backendUser, HttpSession session) {
        BackendUser user = (BackendUser) session.getAttribute("userSession");
        backendUser.setModifyBy(user.getId());
        backendUser.setModifyDate(new Date());
        System.out.println(backendUser.toString());
        int count = 0;
        try {
            count = backendUserServiceImpl.updateBackendUserBiz(backendUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (count > 0) {
            return "redirect:/manager/backend/user/list";
        } else {
            return "backend/user/view";
        }
    }
}
